package sys.knot.configuration;


import org.slf4j.Logger;
import sys.knot.util.KnotPaths;

import javax.annotation.PostConstruct;
import javax.ejb.Startup;
import javax.ejb.Singleton;
import javax.inject.Inject;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

@Singleton
@Startup
public class ApplicationConfiguration {

    private static final String SERVICE_FILE_PATTERN = "*.service.yaml";

    private Map<String, ServiceConfiguration> services = new HashMap<>();

    @Inject
    private Logger logger;

    @Inject
    private KnotPaths knotPaths;

    @PostConstruct
    public void loadConfig() {
        logger.info("Start configuration loading process...");

        try (DirectoryStream<Path> ds = Files.newDirectoryStream(knotPaths.getServiceDir(), SERVICE_FILE_PATTERN)){
            for (Path p : ds) {
                logger.debug("Loading service from file: " + p);
                ServiceConfiguration t = new ServiceConfiguration(p, knotPaths);
                services.put(t.getServiceMethod() + t.getServiceEndPoint(), t);
                t.echoDetails();
            }
        } catch (IOException | ConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        logger.info("Configuration loaded, loaded " + services.size() + " services: " + services.values());
    }


    public ServiceConfiguration getServiceConfiguration(String method, String endPoint) {
        return services.get(method + endPoint);
    }
}
